#include	<Script.h>
#include	<IniFile.h>
#include	<CsvFile.h>
#include	<Logger.h>

namespace {
	int LoadCsv(LuaStack & r) {
		std::string path = r.Get<std::string>(1);
		int header = r.Top() >= 2 ? r.Get<int>(2) : 0;

		CsvFile file;
		if (!file.Load(path, header, '\t')) {
			LOG_ERR("Failed to load CSV file : %s", path.c_str());
			return 0;
		}

		auto keys = file.Headers();
		LuaTable t;

		for (size_t i = 0; i < file.Count(); ++i) {
			LuaTable one;
			for (auto & key : keys) {
				one.Set<std::string>(key, file.Get<std::string>((int)i, key, ""));
			}
			t.Set<LuaTable>((int)i, one);
		}

		r.Push<LuaTable>(t);
		return 1;
	}

	int LoadIni(LuaStack & r) {
		std::string path = r.Get<std::string>(1);

		IniFile file;
		if (!file.Load(path)) {
			LOG_ERR("Failed to load INI file : %s", path.c_str());
			return 0;
		}

		auto sessions = file.GetSessions();
		LuaTable t;

		for (auto & session : sessions) {
			auto keys = file.GetKeys(session);
			LuaTable one;
			for (auto & key : keys) {
				one.Set<std::string>(key, file.Get<std::string>(session, key, ""));
			}
			t.Set<LuaTable>(session, one);
		}
		
		r.Push<LuaTable>(t);
		return 1;
	}
}

void RegisterLuaApi_File() {
	GLua.Register("File")
		.Method("LoadCsv", &LoadCsv)
		.Method("LoadIni", &LoadIni);
}